import { Controller, Inject, Get, Post, Body, Del } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { UserEntity } from '../entity/user.entity';
import { MessageEntity } from '../entity/message.entity';
import { Repository } from 'typeorm';
import { JwtPassportMiddleware } from '../middleware/jwt.middleware';
import { checkEssentialParams, getUserFromToken } from '../utils';
import { JwtService } from '@midwayjs/jwt';
import { UserService } from '../service/user.service';

interface AddMessage {
  title: string;
  content: string;
}

// 该控制器主要用于处理留言信息(XSS Store)相关业务
@Controller()
export class XssStoreController {
  @Inject()
  ctx: Context;

  @Inject()
  jwt: JwtService;

  @Inject()
  userService: UserService;

  @InjectEntityModel(UserEntity)
  userModal: Repository<UserEntity>;

  @InjectEntityModel(MessageEntity)
  messageModal: Repository<MessageEntity>;

  @Get('/message', { middleware: [JwtPassportMiddleware] })
  async getMessages() {
    return await getUserFromToken(this.ctx, this.jwt, this.userService).then(
      ({ messages }) => (messages ? messages : [])
    );
  }

  @Post('/message', { middleware: [JwtPassportMiddleware] })
  async addMessage(@Body() { title, content }: AddMessage) {
    checkEssentialParams(title, content);
    const target = await getUserFromToken(this.ctx, this.jwt, this.userService);
    const newMessage = new MessageEntity(target, title, content);
    target.messages = target?.messages
      ? [...target.messages, newMessage]
      : [newMessage];
    await this.userModal.save(target);
    await this.messageModal.save(newMessage);
    return await this.getMessages();
  }

  @Del('/message', { middleware: [JwtPassportMiddleware] })
  async removeMessage() {
    const target = await getUserFromToken(this.ctx, this.jwt, this.userService);
    return await this.messageModal.delete(target.messages.map(i => i.id));
  }
}
